package com.ttc.ssm.controller.home;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttc.ssm.common.DeliveryPage;
import com.ttc.ssm.common.JobPage;
import com.ttc.ssm.common.MailPage;
import com.ttc.ssm.controller.common;
import com.ttc.ssm.po.*;
import com.ttc.ssm.service.admin.CustomerService;
import com.ttc.ssm.service.home.HomeCommonService;
import com.ttc.ssm.service.home.HomeCompanyService;
import com.ttc.ssm.service.home.HomeCustomerService;
import com.ttc.ssm.service.home.HomeJobService;
import com.ttc.ssm.utils.FileUtils;
import com.ttc.ssm.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

/**
 * Created by 58296 on 2016/8/5.
 */
@Controller
@RequestMapping("home/customer")
public class HomeCustomerController {

    @Autowired
    CustomerService customerService;

    @Autowired
    HomeCustomerService homeCustomerService;

    @Autowired
    HomeJobService homeJobService;

    @Autowired
    HomeCompanyService homeCompanyService;

    @Autowired
    HomeCommonService homeCommonService;

    @RequestMapping("personal")
    public String personal(HttpSession session, Model model) throws Exception
    {
        Integer customer_id =(Integer) session.getAttribute("customer_id");
        if (customer_id <= 0) {
            model.addAttribute("msg","该用户不存在！");
            return "forward:/WEB-INF/jsp/home/login.jsp";
        }
        Map map = new HashMap();
        map.put("customer_id", customer_id);
        map.put("status", -1);
        int delivery_num = homeCustomerService.countDeliveryRowsByMap(map);
        map.put("status", 1);
        int delivery_success = homeCustomerService.countDeliveryRowsByMap(map);
        int invite_num = homeCustomerService.countInviteRowsByCustomerId(customer_id);
        Customer customer = customerService.getCustomerById(customer_id);
        model.addAttribute("customer",customer);
        model.addAttribute("delivery_num", delivery_num);
        model.addAttribute("delivery_success", delivery_success);
        model.addAttribute("invite_num", invite_num);
        return "home/customer/personal";
    }

    @RequestMapping("edit")
    public String edit(HttpSession session, Model model) throws Exception
    {
        Integer customer_id =(Integer) session.getAttribute("customer_id");
        if (customer_id <= 0) {
            model.addAttribute("msg","该用户不存在！");
            return "forward:/WEB-INF/jsp/home/login.jsp";
        }
        Customer customer = customerService.getCustomerById(customer_id);
        model.addAttribute("customer", customer);
        return "home/customer/edit";
    }

    @RequestMapping("/checkExistCustomerEmail")
    public @ResponseBody
    String checkExistCustomerEmail(@RequestParam("email") String email,@RequestParam("customer_id") Integer customer_id) throws Exception
    {
        boolean result = true;
        Map where = new HashMap();
        where.put("email",email);
        where.put("telephone",null);
        where.put("customer_id", customer_id);
        if(homeCustomerService.checkExist(where) >= 1){
            result = false;
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/checkExistCustomerPhone")
    public @ResponseBody String checkExistCustomerPhone(@RequestParam("telephone") String telephone, @RequestParam("customer_id") Integer customer_id) throws Exception
    {
        boolean result = true;
        Map where = new HashMap();
        where.put("email",null);
        where.put("telephone",telephone);
        where.put("customer_id",customer_id);
        if(homeCustomerService.checkExist(where) >= 1){
            result = false;
        }
        Map<String, Boolean> map = new HashMap();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        resultString = mapper.writeValueAsString(map);
        return resultString;
    }

    @RequestMapping("/saveCustomer")
    public String saveCustomer(Customer customer, MultipartFile input01, Model model, HttpServletRequest request) throws Exception {
        if("".equals(customer.getFullname())||customer.getFullname() == null || !common.isstring(customer.getFullname())){
            model.addAttribute("customer",customer);
            model.addAttribute("msg",1);
            return "forward:/home/customer/edit.action";
        }
        if("".equals(customer.getEmail())||customer.getEmail() == null){
            model.addAttribute("customer",customer);
            model.addAttribute("msg",2);
            return "forward:/home/customer/edit.action";
        }
        if(!common.checkEmail(customer.getEmail())){
            model.addAttribute("customer",customer);

            model.addAttribute("msg",6);
            return "forward:/home/customer/edit.action";
        }
        if("".equals(customer.getTelephone())||customer.getTelephone() == null){
            model.addAttribute("customer",customer);
            model.addAttribute("msg",3);
            return "forward:/home/customer/edit.action";
        }
        if(!common.checkMobileNumber(customer.getTelephone())){
            model.addAttribute("customer",customer);

            model.addAttribute("msg",7);
            return "forward:/home/customer/edit.action";
        }

        Map map = new HashMap();
        map.put("email",customer.getEmail());
        map.put("telephone",null);
        map.put("customer_id",customer.getCustomer_id());
        if(homeCustomerService.checkExist(map) >= 1){
            model.addAttribute("customer",customer);
            model.addAttribute("msg",9);
            return "forward:/home/customer/edit.action";
        }
        Map map1 = new HashMap();
        map1.put("email",null);
        map1.put("telephone",customer.getTelephone());
        map1.put("customer_id",customer.getCustomer_id());
        if(homeCustomerService.checkExist(map1) >= 1){
            model.addAttribute("customer",customer);
            model.addAttribute("msg",10);
            return "forward:/home/customer/edit.action";
        }
        try{
            String originalFilename = input01.getOriginalFilename();
            System.out.println(originalFilename);
            String name = FileUtils.createFile(input01,request);
            if (!TextUtils.isEmpty(name)) {
                customer.setHeadimgurl(name);
                Customer tmp_customer = customerService.getCustomerById(customer.getCustomer_id());
                if (!TextUtils.isEmpty(tmp_customer.getHeadimgurl())) {
                    deleteFile(tmp_customer,request);
                }
            }
            int customer_id = homeCustomerService.update_customer(customer,request);
            model.addAttribute("customer", customer);
            model.addAttribute("success",1);
            return "forward:/home/customer/edit.action";
        }catch (Exception e){
            model.addAttribute("customer",customer);
            model.addAttribute("error",1);
            return "forward:/home/customer/edit.action";
        }
    }

    @RequestMapping("changePsd")
    public String changePsd(HttpSession session, Model model) throws Exception
    {
        Integer customer_id =(Integer) session.getAttribute("customer_id");
        if (customer_id <= 0) {
            model.addAttribute("msg","该用户不存在！");
            return "forward:/WEB-INF/jsp/home/login.jsp";
        }

        Customer customer = new Customer();
        customer.setCustomer_id(customer_id);
        customer.setPassword(null);
        model.addAttribute("customer", customer);
        return "home/customer/changePsd";
    }

    @RequestMapping("savePsd")
    public String savePsd(Customer customer, @RequestParam("old_password") String old_password, @RequestParam("confirm_password") String confirm_password,
                       Model model) throws Exception
    {
        if(TextUtils.isEmpty(old_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("confirm_password",confirm_password);
//            model.addAttribute("old_password", old_password);
            model.addAttribute("msg",1);
            return "forward:/home/customer/changePsd.action";
        }
        if(TextUtils.isEmpty(customer.getPassword()) || customer.getPassword().length() < 6 || customer.getPassword().length()>20){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",2);
            return "forward:/home/customer/changePsd.action";
        }
        if(TextUtils.isEmpty(confirm_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",3);
            return "forward:/home/customer/changePsd.action";
        }
        if(!customer.getPassword().equals(confirm_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",4);
            return "forward:/home/customer/changePsd.action";
        }
        Customer tmp = customerService.getCustomerById(customer.getCustomer_id());
        if(!tmp.getPassword().equals(common.SHA1(tmp.getSalt()+common.SHA1(tmp.getSalt()+common.SHA1(old_password))))){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",5);
            return "forward:/home/customer/changePsd.action";
        }

        try{
            customer.setSalt(tmp.getSalt());
            int customer_id = homeCustomerService.save_psd(customer);
            model.addAttribute("success",1);
            return "forward:/home/customer/changePsd.action";
        }catch (Exception e){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("error",1);
            return "forward:/home/customer/changePsd.action";
        }
    }

    public static void deleteFile(Customer customer, HttpServletRequest request) {

        if (!(customer.getHeadimgurl() ==null)){
            String pic_path=request.getSession().getServletContext().getRealPath("upload/customer/");
            String old_file_name = pic_path+customer.getHeadimgurl();
            File old_File = new File(old_file_name);
            if(old_File.exists()){
                old_File.delete();
            }
        }
    }

    @RequestMapping("notice")
    public String notice() throws Exception
    {
        return "home/customer/notice";
    }

    @RequestMapping("/getNoticeList")
    @ResponseBody
    public Map getNoticeList(HttpSession session, @RequestParam("p") int p, @RequestParam("select") int select) throws Exception
    {
        DeliveryPage deliveryPage = new DeliveryPage();
        deliveryPage.setPageSize(3);
        deliveryPage.setCurrentPage(p);
        int customer_id = (Integer) session.getAttribute("customer_id");
        deliveryPage.setCustomer_id(customer_id);
        if (select == 3){
            deliveryPage.setStatus(1);
        }
        Map map = new HashMap();
        List<Delivery> deliveryList = new ArrayList<Delivery>();
        List<Invite> inviteList = new ArrayList<Invite>();
        if (select == 1) {
            deliveryPage.setTotalRows(homeCustomerService.countRows(deliveryPage));
            deliveryList = homeCustomerService.selectDeliveryForPage(deliveryPage);
            map.put("data",deliveryList);
        }else if (select == 2) {
            deliveryPage.setTotalRows(homeCustomerService.countInviteRows(deliveryPage));
            inviteList = homeCustomerService.selectInviteForPage(deliveryPage);
            map.put("data",inviteList);
        }else if (select == 3) {
            deliveryPage.setTotalRows(homeCustomerService.countRows(deliveryPage)+homeCustomerService.countInviteRows(deliveryPage));
            deliveryList = homeCustomerService.selectDeliveryForPage(deliveryPage);
            inviteList = homeCustomerService.selectInviteForPage(deliveryPage);
            List  list  =  new ArrayList();
            list.add(deliveryList);
            list.add(inviteList);
            map.put("data", inviteList);
        }
        map.put("show", deliveryPage);
        return map;
    }

    @RequestMapping("jobDetail")
    public String jobDetail (Model model , @RequestParam("job_id") int jobId ) throws Exception
    {
        Job job = homeJobService.selectJobById(jobId);
        model.addAttribute("job",job);
        String industryName = homeJobService.getIndustryNameById(job.getJobType().getIndustry_id());
        model.addAttribute("industryName",industryName);
        List<JobTag> jobTagList = homeJobService.getJobTab(job.getCompany_id());
        model.addAttribute("jobTagList",jobTagList);
        List<TagToJob> tagToJobList = homeJobService.getTagForJob(jobId);
        model.addAttribute("tagToJobList",tagToJobList);
        Company company = homeCompanyService.selectCompanyById(job.getCompany_id());
        model.addAttribute("company",company);
        CompanyDetail companyDetail = homeCompanyService.selectCompanyDetail(job.getCompany_id());
        model.addAttribute("companyDetail",companyDetail);
        return "home/customer/jobDetail";
    }

    @RequestMapping("jobDetailForSend")
    public String jobDetailForSend (Model model , @RequestParam("job_id") int jobId ) throws Exception
    {
        Job job = homeJobService.selectJobById(jobId);
        model.addAttribute("job",job);
        String industryName = homeJobService.getIndustryNameById(job.getJobType().getIndustry_id());
        model.addAttribute("industryName",industryName);
        List<JobTag> jobTagList = homeJobService.getJobTab(job.getCompany_id());
        model.addAttribute("jobTagList",jobTagList);
        List<TagToJob> tagToJobList = homeJobService.getTagForJob(jobId);
        model.addAttribute("tagToJobList",tagToJobList);
        Company company = homeCompanyService.selectCompanyById(job.getCompany_id());
        model.addAttribute("company",company);
        CompanyDetail companyDetail = homeCompanyService.selectCompanyDetail(job.getCompany_id());
        model.addAttribute("companyDetail",companyDetail);
        return "home/customer/jobDetailForSend";
    }

    @RequestMapping("mail_box")
    public String mail_box() throws Exception
    {
        return "home/customer/mail_box";
    }

    @RequestMapping("/getMailList")
    @ResponseBody
    public Map getMailList(HttpSession session, @RequestParam("p") Integer page, @RequestParam("select") Integer select) throws Exception
    {
        MailPage mailPage = new MailPage();
        mailPage.setPageSize(10);
        mailPage.setCurrentPage(page);
        if (select == 1) {
            mailPage.setIs_read(0);
        }else if (select == 2) {
            mailPage.setIs_read(1);
        }
        int customer_id = (Integer) session.getAttribute("customer_id");
        System.out.println("================>"+customer_id);
        if (customer_id > 0) {
            mailPage.setCustomer_id(customer_id);
        }
        mailPage.setTotalRows(homeCustomerService.countRowsNoReadCustomerDeliveryForEmail(mailPage));
        List<DeliveryActivity> deliveryActivities = homeCustomerService.selectDeliveryActivityCustomerForMail(mailPage);

        Map map = new HashMap();
        map.put("data",deliveryActivities);
        map.put("show",mailPage);
        return map;
    }

    @RequestMapping("/getMailList1")
    @ResponseBody
    public Map getMailList1(HttpSession session, @RequestParam("p") Integer page, @RequestParam("select") Integer select) throws Exception
    {
        MailPage mailPage = new MailPage();
        mailPage.setPageSize(10);
        mailPage.setCurrentPage(page);
        if (select == 1) {
            mailPage.setIs_read(0);
        }else if (select == 2) {
            mailPage.setIs_read(1);
        }
        int customer_id = (Integer) session.getAttribute("customer_id");
        System.out.println("================>"+customer_id);
        if (customer_id > 0) {
            mailPage.setCustomer_id(customer_id);
        }
        mailPage.setTotalRows(homeCustomerService.countRowsNoReadCustomerForEmail(mailPage));
        List<InviteActivity> inviteActivities = homeCustomerService.selectActivityCustomerForPage(mailPage);

        Map map = new HashMap();
        map.put("data",inviteActivities);
        map.put("show",mailPage);
        return map;
    }

    @RequestMapping("/read")
    @ResponseBody
    public Map read(@RequestParam("id") Integer id) throws Exception
    {
        Map data = new HashMap();
        data.put("id",id);
        data.put("is_read",1);
        try{
            homeCommonService.updateIsRead(data);
            Map map = new HashMap();
            map.put("code",1);
            return map;
        }catch (Exception e){

            Map map = new HashMap();
            map.put("code",0);
            return map;
        }
    }

    @RequestMapping("/acceptOrRefuse")
    @ResponseBody
    public Map acceptOrRefuse(HttpSession session,@RequestParam("invite_activity_id") Integer invite_activity_id,@RequestParam("id") Integer id,@RequestParam("type") Integer type,@RequestParam("company_id") Integer company_id,@RequestParam("resume_id") Integer resume_id,@RequestParam("job_id") Integer job_id) throws Exception
    {
        try{
            Map data = new HashMap();
            data.put("status",type);
            data.put("invite_id",id);
            homeCommonService.updateInviteStatus(data);
            Map data1 = new HashMap();
            data1.put("id",invite_activity_id);
            data1.put("is_read",1);
            homeCommonService.updateIsReadInvite(data1);
            InviteActivity inviteActivity = new InviteActivity();
            int customer_id = (Integer) session.getAttribute("customer_id");
            inviteActivity.setCustomer_id(customer_id);
            inviteActivity.setCompany_id(company_id);
            inviteActivity.setIs_read(0);
            inviteActivity.setInvite_id(id);
            inviteActivity.setType(1);
            inviteActivity.setStatus(type);
            inviteActivity.setDate_added(new Date());
            homeCommonService.insertInviteActivity(inviteActivity);
            if(type == 1){
                Delivery delivery = new Delivery();
                delivery.setResume_id(resume_id);
                delivery.setCustomer_id(customer_id);
                delivery.setCompany_id(company_id);
                delivery.setJob_id(job_id);
                delivery.setStatus(1);
                delivery.setDate_added(new Date());
                homeCommonService.insertDeliveryWhenAccept(delivery);
            }
            Map map = new HashMap();
            map.put("code",1);
            return map;
        }catch (Exception e) {

            Map map = new HashMap();
            map.put("code",0);
            return map;
        }
    }

}
